<template>
	<view>
		<nav-bar title="衷依慧店" :showLeftIcon="false"></nav-bar>

		<search placeholder="搜索门店"  :leftSlot="true" @searchFocus="searchFocus" >
			<!-- disabled='true' -->
			<template #leftSlot>
				<view class="city" @click="toCity">
					<uni-icons type="location" size="20" color="#fff"></uni-icons>
					<view style="margin: 0 10rpx;">{{ city }}</view>
					<uni-icons type="bottom" size="12" color="#fff"></uni-icons>
				</view>
			</template>
		</search>

		<view class="u-demo-block">
			<u-swiper :list="bannerList" @change="changeBanner" :autoplay="true" radius="8" height="180" interval="5000"
				@click="swiper" keyName="img" :indicator="true">
				<view slot="indicator" class="indicator">
					<view v-for="(item, index) in bannerList" :key="index"
						:class="['indicator__dot', index === bannerCurrent && 'indicator__dot--active']"></view>
				</view>
			</u-swiper>
		</view>

		<view class="common-title">
			<view class="box-line"></view>
			<view class="text">请选择预约门店</view>
		</view>

		<scroll-view scroll-y :style="{ height: scrollHeight }" class="contain">
			<view v-if="isLoading" class="common-loading">
				<image class="loading-img" :src="baseIconUrl + 'icon_loading.png'" />
			</view>
			<view v-else-if="shopData && shopData.length > 0">
				<shop-list :shopConfig="shopData" @toDetail="clickToDetail" @changeStatus="changeStatus"
					@toPreserve="toPreserve"></shop-list>
			</view>
			<view v-else class="common-no-data">
				<image class="no-data-img" :src="baseImgUrl + 'img_no_address.png'" alt="" />
				<view class="text">暂无门店</view>
			</view>
		</scroll-view>
		<view>
			<u-picker :show="show" :columns="columns" title="选择城市" confirmColor="rgba(194, 126, 21, 1)"
				:closeOnClickOverlay="true" @confirm="confirm" @cancel="cancel"></u-picker>
		</view>
		<u-overlay :show="couponShow">
			<view class="warp">
				<view class="rect">
					<view class="close">
						<u-icon name="close-circle" color="#fff" size="28" @click="couponShow = false"></u-icon>
					</view>
					<image class="img" :src="baseImgUrl + 'img_index_coupon.png'" alt="" @click="clickReceive" />
					<view class="cardTitle">恭喜获得<span style="color: #fe5d41;">
							{{couponData.couponNumber || 0}}张</span>抵用券
					</view>
					<view class="card">
						<view class="card-money" v-if="couponData.couponList[0].discountsType==2">
							<u-icon name="rmb" color="#fff" size="22"></u-icon>
							<view class="money">{{ couponData.couponList[0].discountAmount }}</view>
						</view>
						<view class="card-money" v-else>
							<!-- <u-icon name="rmb" color="#fff" size="15"></u-icon> -->
							<view class="money">{{ couponData.couponList[0].discountRate }}折</view>
						</view>
						<view class="card-title">
							<view class="tit">{{ couponData.couponList[0].name }}</view>
							<!-- <view class="date">{{ couponData.effectiveTime}}到期</view>-->
							<view class="date">优惠类型：{{couponData.couponList[0].discountsType==1?'折扣券':'立减券'}}</view>
						</view>
					</view>
				</view>
			</view>
		</u-overlay>
	<you-popup :popupVisible="stopVisible" popupTitle="温馨提示" @popupClose="stopVisible = false"
		@cancel="clickCancel" @confirm="clickConfirm" bgColor="#fff">
		<view slot="popupContent">
			<!-- 标题 -->
			<view class="contain-text">
				{{ popupFlag === 1 ? ` 您选择的门店因${stopMaessage.pauseCause}原因暂停营业，预${stopMaessage.startBusinessTime}恢复营业，请选择其他门店。`
	  : `该门店正在筹备中，暂无法为您提供服务，预计开业时间${stopMaessage.startBusinessTime}` }}
			</view>
		</view>
		<view slot="btnBox" class="popup-submit flexJcac">
			<view class="submit" @click="stopVisible = false">{{ popupFlag === 1 ? '确定' : '是' }}</view>
		</view>
	</you-popup>
	</view>
</template>

<script>
	import YouPopup from "../components/you-popup/index.vue"
	import YouScroll from '@/components/you-scroll/index'
	import NavBar from "../components/nav-bar"
	import Search from '../components/search/index'
	import ShopList from "@/subPages/components/shopList"
	import {
		getToken
	} from '@/utils/auth'
	import api_home from '@/api/home'
	import api_common from '@/api/common'
	import api_mine from '@/api/mine'
	import pageConfig from '@/config'
	import store from "../store"
	export default {
		name: "index",
		components: {
			YouScroll,
			NavBar,
			Search,
			ShopList,
			YouPopup
		},
		data() {
			return {
				stopVisible: false,
				baseUrl: pageConfig.baseUrl,
				baseImgUrl: pageConfig.baseImgUrl,
				baseIconUrl: pageConfig.baseIconUrl,
				columns: [
					[],
					[],
					[]
				],
				defaultIndex: [], // 设置默认选中值为第一列的第二项和第二列的第三项
				heightConfig: {},
				scrollHeight: '',
				couponShow: false,
				couponData: {},
				token: getToken(),
				bannerCurrent: 0,
				bannerList: [],
				shopData: [],
				isLoading: false,
				cityList: [],
				cityParams: {},
				popupFlag: '',
				stopVisible: false,
				show: false,
				cityName: '',
				currentMonth: '',
				currentYear: '',
				transferData: {},
				latitude: '',
				longitude: '',
				stopMaessage:{}
			}
		},
		onShow() {
			this.$store.commit('TECHNICIAN_NUMBER', {})
			this.getLocation()
		},
		created() {
			this.heightConfig = this.$store.getters.heightData
			this.scrollHeight = this.heightConfig.mainSearchHeight.split("px")[0] - 256 + "px"
			if (this.token) {
				this.getUserInfo()
			}
			var currentDate = new Date()
			// 获取当前月份
			var currentMonth = currentDate.getMonth() + 1
			this.currentMonth = currentMonth < 10 ? `0${currentMonth}` : currentMonth // 补零使月份两位数
			// 获取该月的天数
			var currentYear = currentDate.getFullYear()
			this.currentYear = currentYear
			const daysInMonth = new Date(currentYear, currentMonth, 0).getDate()
			var daysArray = Array.from({
				length: daysInMonth
			}, (_, i) => i + 1)
			var houreArray = Array.from({
				length: 24
			}, (_, i) => i + 1)
			this.columns[0] = daysArray
			this.columns[1] = houreArray
			this.columns[2] = [0, 10, 20, 30, 40, 50]
		},
		computed: {
			city() {
				return this.$store.getters.cityName
			}
		},
		mounted() {
			uni.$on('city', (data) => {
				const list = this.cityList.filter((item) => {
					return item.cityName === data.city
				})
				store.commit('CITY_NAME', data.city)
				store.commit('CITY_DATA', {
					latitude: this.latitude,
					longitude: this.longitude,
					cityString: this.$store.getters.cityName
				})
				this.getShopList(data.reload)
			})
		},
		methods: {
			getUserInfo() {
				api_mine.fetchUserInfo().then(res => {
					if (res.code !== 200) return
					this.userInfo = res.data
					uni.setStorageSync('userInfo', res.data)
				})
			},
			swiper(item, index) {
				// uni.switchTab({
				// 	url: this.bannerList[item].urls
				// })
			},
			getData() {
				if (this.userInfo) {
					this.getSysCouponList()
				}
				this.getBanner()
				this.getShopList()
				this.getAllCity()
			},
			getSysCouponList() {
				const params = {
					state: 1,
					getPath: 1,
					couponTypeValue: 1,
					couponType: '平台券'
				}
				api_home.fetchSysCouponList(params).then(res => {
					console.log(res, 'res');
					if (res.code !== 200) return
					this.couponData = res.data
					if (res.data.couponNumber != 0){
						this.couponShow = true
					}
				})
			},
			clickReceive() {
				if (!this.token) {
					this.$tab.navigateTo('/subPages/home/login')
				} else {
					const params = {
						couponTypeValue: 1,
						getPath: 1
					}
					api_home.receiveCoupon(params).then(res => {
						if (res.code !== 200) return
						uni.showToast({
							title: '领取成功，请前往个人中心查看',
							icon: 'none'
						})
						this.couponShow = false
					})
				}
			},
			getBanner() {
				api_home.fetchBannerList().then((res) => {
					if (res.code !== 200) return
					this.bannerList = res.data
				})
			},
			changeBanner(e) {
				this.bannerCurrent = e.current
			},
			getShopList(reload = false) {
				this.isLoading = true
				const params = {
					cityString: reload ? this.$store.getters.cityData.cityString : '',
					latitude: this.$store.getters.cityData.latitude,
					longitude: this.$store.getters.cityData.longitude,
					minProIsShow: 1
				}
				api_home.fetchShopList(params).then((res) => {
					this.isLoading = false
					if (res.data.length > 0) {
						res.data.forEach((item) => {
							item.images = item.images.split(",")[0]
						})
						this.shopData = res.data
					} else {
						this.shopData = []
					}
				}).catch(err => {
					this.isLoading = false
				})
			},
			getAllCity() {
				api_common.fetchAllCity().then((res) => {
					this.cityList = res.data
				})
			},
			cancel() {
				this.show = false
			},
			clickToDetail(item) {
				const storeAddress = item.provinceString + item.cityString + item.countyString + item.detail
				const transferData = {
					storeId: item.id,
					storeName: item.storeName,
					regionId: item.regionId,
					regionName: item.regionName,
					storeAddress,
					openingTime: item.openingTime,
					closingTime: item.closingTime
				}
				const params = encodeURIComponent(JSON.stringify(transferData))
				uni.navigateTo({
					url: `/subPages/home/shopDetail?transferData=${params}`
				})
			},
			toPreserve(item) {
				if (!this.token) {
					this.$tab.navigateTo('/subPages/home/login')
					return
				}
				console.log(item,'.....	 item');
				if (item.status != 1) {
					let message = item.status == 2 ? this.popupFlag = 2 : this.popupFlag = 1
					this.stopVisible = true
					this.stopMaessage = item
					return;
				}
				const storeAddress = item.provinceString + item.cityString + item.countyString + item.detail
				const transferData = {
					storeId: item.id,
					storeName: item.storeName,
					regionId: item.regionId,
					regionName: item.regionName,
					storeAddress,
					openingTime: item.openingTime,
					closingTime: item.closingTime
				}
				const params = encodeURIComponent(JSON.stringify(transferData))
				uni.navigateTo({
					url: `/subPages/home/chooseProject?transferData=${params}`
				})
			},
			changeStatus(item) {
				if (item.status === 1) {
					this.popupFlag = 2
					this.stopVisible = true
				}
			},
			getLocation() {
				uni.getLocation({
					provider: 'system',
					success: (res) => {
						store.commit('CITY_DATA', {
							latitude: res.latitude,
							longitude: res.longitude
						})
					}
				})
				uni.getLocation({
					type: 'gcj02',
					success: res => {
						const latitude = res.latitude.toFixed(6)
						const longitude = res.longitude.toFixed(6)
						this.latitude = latitude
						this.longitude = longitude
						this.reverseGeocode(res.longitude, res.latitude)
					},
					fail: err => {
						console.log('定位失败:', err);
					}
				})
			},
			reverseGeocode(longitude, latitude) {
				uni.request({
					method: 'get',
					url: 'https://restapi.amap.com/v3/geocode/regeo',
					data: {
						key: '6b9fb008bdd4abde0a32433a82ff06cd',
						location: `${longitude},${latitude}`,
						extensions: 'base',
						output: 'json',
					},
					success: (res) => {
						if (res.data.status === '1') {
							if (res.data.regeocode && res.data.regeocode.formatted_address) {
								const address = res.data.regeocode.addressComponent.city
								store.commit('CITY_NAME', address)
								store.commit('CITY_DATA', {
									...this.$store.getters.cityData,
									cityString: this.$store.getters.cityName
								})
								this.getData()
							} else {
								console.error('无法获取地址信息');
							}
						} else {
							console.error('逆地理编码请求失败');
						}
					},
					fail: (err) => {
						console.error(err)
					}
				})
			},
			searchFocus(value) {
				// console.log(value,'value');
				const params = encodeURIComponent(JSON.stringify(this.$store.getters.cityData));
				this.$tab.navigateTo(`/subPages/home/searchShop?params=${params}&searchValue=${value}`)
			},
			toCity() {
				uni.removeStorageSync('chooseTechnician')
				this.$tab.navigateTo('/subPages/home/city')
			},
			getCity() {
				uni.getStorage({
					key: 'City_Name',
					success: function(res) {
						console.log(res.data);
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.warp {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100%;
	}

	.rect {
		// width: 120rpx;
		// height: 120rpx; 
		// background-color: #fff;
		// width: 800rpx;
		// height: 1400rpx;
		position: relative;

		// background-color: red;
		.close {
			position: absolute;
			top: 22%;
			right: 9%;
			z-index: 5;
		}

		.img {
			width: 800rpx;
			height: 1400rpx;
			// background-color: #fff;
		}

		.cardTitle {
			position: absolute;
			bottom: 62.5%;
			left: 21%;
			font-size: 52rpx;
			font-weight: 600;
			color: #7c2a10;
		}

		.card {

			color: #fff;
			display: flex;

			.card-money {
				position: absolute;
				bottom: 47%;
				left: 22%;
				display: flex;
				font-size: 65rpx;
				font-family: DIN, DIN;
				font-weight: bold;
			}

			.card-title {
				.tit {
					position: absolute;
					bottom: 51%;
					width: 300rpx;
					right: 18%;
					font-size: 34rpx;
					font-family: Source Han Sans CN, Source Han Sans CN;
					font-weight: 500;
				}

				.date {
					position: absolute;
					bottom: 47%;
					right: 30%;
					font-size: 24rpx;
					font-family: Source Han Sans CN, Source Han Sans CN;
					font-weight: 400;
				}
			}
		}
	}

	::v-deep .u-demo-block {
		height: 200px;
		padding: 20rpx;
	}

	.indicator {
		@include flex(row);
		justify-content: center;

		&__dot {
			height: 6px;
			width: 6px;
			border-radius: 100px;
			background-color: rgba(255, 255, 255, 0.35);
			margin: 0 5px;
			transition: background-color 0.3s;

			&--active {
				background-color: #ffffff;
			}
		}
	}

	.indicator-num {
		padding: 2px 0;
		background-color: rgba(0, 0, 0, 0.35);
		border-radius: 100px;
		width: 35px;
		@include flex;
		justify-content: center;

		&__text {
			color: #FFFFFF;
			font-size: 12px;
		}
	}

	.city {
		color: rgba(255, 255, 255, 1);
		display: flex;
		margin-right: 20rpx;
		transform: translateY(15rpx);
	}

	.common-title {
		height: 55px;
		border-radius: 24rpx 24rpx 0 0;
		background-color: #FFF;
		position: relative;
		z-index: 2;
	}

	.contain {
		background-color: #fff;
		width: 100%;
	}
</style>